package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.BuyBean;
import com.project.bean.BuyCarBean;
import com.project.mapper.IBuyCarMapper;
import com.project.service.IBuyCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BuyCarServiceImpl implements IBuyCarService {

    @Autowired
    private IBuyCarMapper buyCarMapper;


    @Override
    public void add(BuyCarBean buyCarBean) {
        buyCarMapper.insert(buyCarBean);
    }

    @Override
    public void updateById(Integer buyCarId, Integer newNum, Integer newPrice) {
        BuyCarBean buyCarBean = buyCarMapper.selectById(buyCarId);
        if (newNum != null){
            buyCarBean.setNum(newNum);
        }
        if (newPrice != null){
            buyCarBean.setPrice(newPrice);
        }
        buyCarMapper.updateById(buyCarBean);
    }

    /**
     *按用户ID，库存商品ID，查询采购车信息。(下列方法第三步)
     *
     * 添加采购商品
     * 输入：操作类型（add/update），库存商品对象，图片上传对象，采购数量
     * 处理：
     * 1、判断操作类型是否为add，如果为add，完成库存商品添加。
     * 2、从session中，取出登陆用户对象。
     * 3、按用户ID，库存商品ID，查询采购车信息。
     * 如果采购车信息为null，则添加采购车记录
     * 如果采购车信息不为null，则累加采购车商品数量
     * 输出：ok
     * @param userId
     * @param goodsId
     * @return
     */
    @Override
    public BuyCarBean findByUserGoods(Integer userId, Integer goodsId,Integer num) {
        QueryWrapper<BuyCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        qw.eq("fk_goodsId",goodsId);
        BuyCarBean buyCarBean = buyCarMapper.selectOne(qw);
//        if (buyCarBean != null){
//            buyCarBean.setNum(buyCarBean.getNum()+num);
//        }else {
//            buyCarBean = new BuyCarBean(0,num,goodsId,userId);
//            buyCarMapper.insert(buyCarBean);
//        }
        return buyCarBean;
    }

    @Override
    public void del(Integer buyCarId) {
        buyCarMapper.deleteById(buyCarId);

    }

    @Override
    public void delMore(Integer userId) {
        QueryWrapper<BuyCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId",userId);
        buyCarMapper.delete(qw);
    }

    @Override
    public List<BuyCarBean> findByUserId(Integer userId) {
        return buyCarMapper.findByUserId(userId);
    }
}
